from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse



from django import forms

from django.template import RequestContext
# ...
import datetime, random, sha

from django.core.mail import send_mail

from CostCalc.HomePage.models import UserProfile, EventProfile
from CostCalc.HomePage.forms import UserProfile, RegistrationForm, EventExpenseForm, CreateEventForm, SetPeopleOnEventForm


def homepage(request):
    #logout(request)
    return render_to_response('HomePage/HomePage.html', {'foo':'bar',},
                               context_instance=RequestContext(request))
    
    
    
def loginpage(request):
    print "Test1"
    state = "Please log in below..."
    username = password = ''
    if request.POST:
        username = request.POST.get('username')
        password = request.POST.get('password')
    
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                state = "You're successfully logged in!"
                return HttpResponseRedirect('../../CostCalc/userhomepage')
            else:
                state = "Your account is not active, please contact the site admin."
        else:
            state = "Your username and/or password were incorrect."

    return render_to_response('HomePage/LoginPage.html',{'state':state, 'username': username},
                                                             context_instance=RequestContext(request))
    
def userhomepage(request):
    if request.user.is_authenticated():
        Events = EventProfile.objects.all()
        return render_to_response('HomePage/userhomepage.html', {'Events':Events},
                               context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect('../../CostCalc/Login')
     

def register(request):
    if request.user.is_authenticated():
        # They already have an account; don't let them register again
        return HttpResponseRedirect('../../CostCalc/Login')
    if request.POST:
        form = RegistrationForm(request.POST)
        if form.is_valid():
            new_user = form.save(form.cleaned_data)
            username = form.cleaned_data['username']
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            new_profile = UserProfile(user=new_user,
                                      #activation_key=activation_key,
                                      #key_expires=key_expires
                                     )
            new_profile.save()
            return HttpResponseRedirect('../../CostCalc/Login')             
        else:
            print form.errors
            return render_to_response('Homepage/signup.html', {'form': form},
                               context_instance=RequestContext(request))
    
    form = RegistrationForm()  
    return render_to_response('Homepage/signup.html', {'form': form},
                               context_instance=RequestContext(request))
    
def CreateEvent(request):
    if request.user.is_authenticated():
        if request.POST:
            form = CreateEventForm(request.POST)
            if form.is_valid():
                Event = form.save(form.cleaned_data)
                return HttpResponseRedirect('../../CostCalc/%d/TripHomepage'%(Event.id))             
            else:
                print form.errors
                return render_to_response('Homepage/CreateEvent.html', {'form': form},
                                   context_instance=RequestContext(request))
        
        form = CreateEventForm()  
        return render_to_response('Homepage/CreateEvent.html', {'form': form},
                                   context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect('/CostCalc/Login')
    
def TripHomepage(request, Event_Id):
    if request.user.is_authenticated():
        try:
            Event = EventProfile.objects.get(id=Event_Id)
        except EventProfile.DoesNotExist:
            return HttpResponseRedirect('/CostCalc/userhomepage')
        EventExpenses = Event.eventexpenseprofile_set.all()
        return render_to_response('Homepage/tripHomePage.html', {'Event': Event, 'EventExpenses' : EventExpenses},
                                   context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect('/CostCalc/Login')
        
        
    
def AddTripExpense(request, Event_Id = 0):
    if request.user.is_authenticated():
        print Event_Id
        print request.user.id
        Event =  EventProfile.objects.get(id=Event_Id)
        if request.POST:
            form = EventExpenseForm(request.POST)
            if form.is_valid():
                user = request.user
                Expense = form.save(form.cleaned_data, request.user.id, Event)
                
                return HttpResponseRedirect('/CostCalc/%d/%d/ViewTripExpense/'%(Event.id, Expense.id))             
            else:
                print form.errors
                return render_to_response('Homepage/AddTripExpense.html', {'form': form, 'Event':Event},
                                   context_instance=RequestContext(request))
    
        form = EventExpenseForm()  
        return render_to_response('Homepage/AddTripExpense.html', {'form': form, 'Event':Event},
                                   context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect('/CostCalc/Login')
def ViewTripExpense(request, Event_Id, Expense_Id):
    if request.user.is_authenticated():
        print Event_Id
        print Expense_Id
        Event =  EventProfile.objects.get(id=Event_Id)
        EventExpense = Event.eventexpenseprofile_set.filter(id = Expense_Id)[0]
        return render_to_response('Homepage/ViewTripExpense.html', {'EventExpense': EventExpense },
                                   context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect('/CostCalc/Login')
        
        
def SetPeopleOnEventForm(request, Event_Id):
    if request.user.is_authenticated():
        print Event_Id
        Event =  EventProfile.objects.get(id=Event_Id)
        if request.POST:
            form = SetPeopleOnEventForm(request.POST)
            #if form.is_valid():
            #    user = request.user
            #    Expense = form.save(form.cleaned_data, request.user.id, Event)
            #    
            #    return HttpResponseRedirect('/CostCalc/%d/%d/ViewTripExpense/'%(Event.id, Expense.id))             
            #else:
            #    print form.errors
            #    return render_to_response('Homepage/AddTripExpense.html', {'form': form, 'Event':Event},
            #                       context_instance=RequestContext(request))
    
        form = SetPeopleOnEventForm()
        form = UserProfile.objects.all()
        return render_to_response('Homepage/AddTripExpense.html', {'form': form, 'Event':Event},
                                   context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect('/CostCalc/Login')